package cn.dakaqi.web;

import cn.dakaqi.entities.*;
import cn.dakaqi.group.recruit.services.GroupRecruitService;
import cn.dakaqi.group.recruit.services.GroupRecruitVolunteerService;
import cn.dakaqi.group.services.GroupMonthDataService;
import cn.dakaqi.group.services.GroupService;
import cn.dakaqi.group.services.GroupVolunteerService;
import cn.dakaqi.member.service.VolunteerService;
import cn.dakaqi.utils.CodeMap;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.Dictionary;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import cn.dakaqi.web.shiro.ShiroDbRealm;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chunyang on 2016/5/12.
 */
public abstract class BaseController
{
    public static final String PAGE_SIZE = "3";

    @Autowired
    GroupMonthDataService groupMonthDataService;
    @Autowired
    GroupRecruitVolunteerService groupRecruitVolunteerService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    GroupService groupService;
    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    GroupRecruitService groupRecruitService;


    //当前用户
    public Volunteer volunteer = null;
    //当前社团
    public Group group = null;
    //当前用户加入的所有社团
    public List<Group> groups = new ArrayList<Group>();
    //服务领域
    public List<Dictionary> userServiceFiled = null;
    //专业技能
    public List<Dictionary> userSkill = null;
    //职业
    public List<Dictionary> userJob = null;
    //网站菜单数据、左路个人数据
    public ModelMap modelMap = null;
    //本社团待审核成员数量
    public int groupWaiteApplys = 0;
    //本社团招募待审核数量
    public int groupRecriuteWaiteApplys = 0;

    public ModelAndView modelAndView = null;
    String key = "";
    public ModelMap initData(String groupCode,HttpServletRequest request)
    {
//        if(StringUtils.isNotBlank(groupCode))
//        {
//            key = "initData_" + groupCode;
//            if(redisClientTemplate.exists(key) && StringUtils.isNotBlank(key))
//            {
//                modelMap = JSON.parseObject(redisClientTemplate.get(key),ModelMap.class);
//            }
//            else
//            {
//                modelMap = new ModelMap();
//                //当前用户信息
//                volunteer = this.volunteerService.findByUserId(getCurrentUserId());
//                if(null == volunteer)
//                    return modelMap;
//                //当用户可以管理的所有组织
//                List<Group> groups = new ArrayList<Group>();
//                List<GroupVolunteer> groupVolunteerList = groupVolunteerService.findByAdmin(volunteer.getMemberCode());
//                if(null != groupVolunteerList && groupVolunteerList.size()>0)
//                {
//                    for(GroupVolunteer gv:groupVolunteerList)
//                        groups.add(gv.getGroup());
//                }
//
//                if(StringUtils.isBlank(groupCode))
//                {
//                    if(null != groups && groups.size()>0)
//                        group = groups.get(groupVolunteerList.size()-1);
//                }
//                else
//                {
//                    group = this.groupService.findByGroupCode(groupCode);
//                }
//
//                //查询当前社团中待审核的人员数量
//
//                //查询当前待挂靠的社团数据
//
//                //服务领域
//                userServiceFiled = CodeMap.getUserServiceFiled();
//                //专业技能
//                userSkill= CodeMap.getUserSkill();
//                //职业
//                userJob = CodeMap.getJob();
//
//                modelMap.addAttribute("userServiceFiled", userServiceFiled);
//                //专业技能
//                modelMap.addAttribute("userSkill", userSkill);
//                //职业
//                modelMap.addAttribute("userJob", userJob);
//                //证件类型
//                modelMap.addAttribute("cardType", CodeMap.getCardType());
//
//                modelMap.addAttribute("volunteer", volunteer);
//                modelMap.addAttribute("group", group);
//                modelMap.addAttribute("groups", groups);
//
//                request.getSession().setAttribute("curGroup",group);
//                request.getSession().setAttribute("volunteer",volunteer);
//                if(null != group)
//                {
//                    //准备图表数据
//                    charData(group.getGroupCode(),modelMap);
//                    //查询本社团加入待审核人数 招募待审核人数
//                    setGroupApplys(group.getGroupCode());
//                }
//
//                redisClientTemplate.set(key, JSON.toJSONString(modelMap));
//            }
//        }
//        else
        {
            modelMap = new ModelMap();
            //当前用户信息
            volunteer = this.volunteerService.findByUserId(getCurrentUserId());
            if(null == volunteer)
                return modelMap;
            //当用户可以管理的所有组织
            List<Group> groups = new ArrayList<Group>();
            List<GroupVolunteer> groupVolunteerList = groupVolunteerService.findByAdmin(volunteer.getMemberCode());
            if(null != groupVolunteerList && groupVolunteerList.size()>0)
            {
                for(GroupVolunteer gv:groupVolunteerList)
                    groups.add(gv.getGroup());
            }

            if(StringUtils.isBlank(groupCode))
            {
                if(null != groups && groups.size()>0)
                    group = groups.get(groupVolunteerList.size()-1);
            }
            else
            {
                group = this.groupService.findByGroupCode(groupCode);
            }

            //查询当前社团中待审核的人员数量

            //查询当前待挂靠的社团数据

            //服务领域
            userServiceFiled = CodeMap.getUserServiceFiled();
            //专业技能
            userSkill= CodeMap.getUserSkill();
            //职业
            userJob = CodeMap.getJob();

            modelMap.addAttribute("userServiceFiled", userServiceFiled);
            //专业技能
            modelMap.addAttribute("userSkill", userSkill);
            //职业
            modelMap.addAttribute("userJob", userJob);
            //证件类型
            modelMap.addAttribute("cardType", CodeMap.getCardType());

            modelMap.addAttribute("volunteer", volunteer);
            modelMap.addAttribute("group", group);
            modelMap.addAttribute("groups", groups);

            request.getSession().setAttribute("curGroup",group);
            request.getSession().setAttribute("volunteer",volunteer);

            if(null != group)
            {
                //准备图表数据
                charData(group.getGroupCode(),modelMap);
                //查询本社团加入待审核人数 招募待审核人数
                setGroupApplys(group.getGroupCode());

                key = "initData_" + group.getGroupCode();
                redisClientTemplate.set(key, JSON.toJSONString(modelMap));
            }
        }

        //查询本社团加入待审核人数 招募待审核人数
        group = (Group)request.getSession().getAttribute("curGroup");
        if(null != group)
        setGroupApplys(group.getGroupCode());
        return modelMap;
    }

    private void setGroupApplys(String groupCode)
    {
        groupRecriuteWaiteApplys = 0;
        //查询本社团待审核的成员数量
        groupWaiteApplys = this.groupVolunteerService.counts(this.groupService.findByGroupCode(groupCode).getId(), DKQConstant.APPLY_STATUS);
        modelMap.addAttribute("groupWaiteApplys", groupWaiteApplys);
        //查询本社团招募待审核人数量
        GroupRecruit groupRecruit = groupRecruitService.findLastByGroupCode(groupCode,DKQConstant.PROCEED_START);
        if(null != groupRecruit)
        {
            List<GroupRecruitVolunteer> list = this.groupRecruitVolunteerService.findVerfierByGroupRecruit(groupRecruit.getId(),DKQConstant.APPLY_STATUS,1);
            if(null != list)
                groupRecriuteWaiteApplys = list.size();
        }
        modelMap.addAttribute("groupRecriuteWaiteApplys", groupRecriuteWaiteApplys);
    }


    private void charData(String groupCode,ModelMap modelMap)
    {
        //categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        StringBuffer categories = new StringBuffer();
        //data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        StringBuffer volunters = new StringBuffer();
        StringBuffer activities = new StringBuffer();
        StringBuffer times = new StringBuffer();
        //
        Page<GroupMonthData> data = this.groupMonthDataService.findByGroupCode(groupCode);
        if(null != data && data.getContent() != null && data.getContent().size()>0)
        {

            for(GroupMonthData gmd:data.getContent())
            {
                String month = gmd.getMonth();
                categories.append("'");
                categories.append(month);
                categories.append("'");
                categories.append(",");


                int _volunteers = gmd.getVolunteers();
                volunters.append(_volunteers);
                volunters.append(",");


                int _activites = gmd.getActivities();
                activities.append(_activites);
                activities.append(",");


                int _times = gmd.getTimes();
                times.append(_times);
                times.append(",");

            }

            modelMap.addAttribute("categories",categories.toString().substring(0,categories.toString().length()-1));
            modelMap.addAttribute("volunters",volunters.toString().substring(0, volunters.toString().length() - 1));
            modelMap.addAttribute("activities",activities.toString().substring(0, activities.toString().length() - 1));
            modelMap.addAttribute("times",times.toString().substring(0, times.toString().length() - 1));

        }
    }
    public void clearInitData()
    {
        redisClientTemplate.del(key);
    }
    protected abstract ModelAndView initModelAndView(String groupCode,String view,HttpServletRequest request);
    protected abstract void clearModelAndView(String groupCode,HttpServletRequest request);
    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

    /**
     * 更新Shiro中当前用户的用户名.
     */
    private void updateCurrentUserName(String userName) {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        user.realName = userName;
    }
}
